#!/bin/bash
#Author: YangYi
#Date: 2025-04-20
#Version: v1
#Content 一键诊断、处置原子能力,节点七层接口拨测
#1.判断节点是否存在与集群
#2.应用创建是否成功
#3.已创建应用七层拨测
#4.清理应用


# ---------------------------初始化全局变量----------------------------

# 检查参数是否传入
if [ -z "$1" ]; then
    echo "错误：请提供NODE节点IP作为参数"
    exit 1
fi

#MASTER_IP=$1
ip="$1"

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 从kubeconfig获取token
CURRENT_CONTEXT=$(kubectl config current-context)
USER=$(kubectl config view -o jsonpath="{.contexts[?(@.name == '${CURRENT_CONTEXT}')].context.user}")
TOKEN=$(kubectl describe secret $(kubectl get secret | grep ^default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t' | tr -d ' ')
APISERVER=$(kubectl config view --minify --flatten --kubeconfig="${KUBECONFIG}" | grep server | cut -d '/' -f3)

# 配置参数
KUBECONFIG="/root/.kube/config"  # 根据实际情况修改kubeconfig路径
NAMESPACE="default"
SERVICE_NAME="nginx-network-service"
DEPLOYMENT_NAME="nginx-network-pod"
CONTAINER_PORT=80


# ----------------------------功能模块函数-----------------------------


# 检查节点是否存在
check_user_input() {

# 验证格式是否为四个数字段
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    
    IFS='.' read -ra ADDR <<< "$ip"
    
    # 检查是否正好包含4个数字段
    if [ ${#ADDR[@]} -ne 4 ]; then
        echo "错误：IP地址必须包含4个数字段"
        exit 1
    fi
 
    # 验证每个数字段的有效性
    valid=1
    for num in "${ADDR[@]}"; do
        # 检查是否为纯数字且不超过255
        if ! [[ $num =~ ^[0-9]+$ ]] || [ $num -gt 255 ]; then
            valid=0
            break
        fi
    done
 
    if [ $valid -eq 1 ]; then
    echo -e "${YELLOW}检查节点: ${ip} 是否存在与集群...${NC}"
    else
        echo -e "${RED}无效的IP地址: 数字段超出范围（0-255）${NC}"
        exit 2
    fi
else
    echo -e "${RED}无效的IP地址: 格式错误（必须为XXX.XXX.XXX.XXX）${NC}"
    exit 3
fi

}

# 检查节点是否存在
check_node_exists() {
    kubectl get nodes --kubeconfig="${KUBECONFIG}" | awk '{print $1}' | grep -v NAME | grep -qw "${ip}"
    return $?
}

# 创建Nginx部署
create_nginx_deployment() {
    curl -s -k -X POST \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer ${TOKEN}" \
        http://${APISERVER}/apis/apps/v1/namespaces/${NAMESPACE}/deployments \
        -d '{
            "apiVersion": "apps/v1",
            "kind": "Deployment",
            "metadata": {
                "name": "'"${DEPLOYMENT_NAME}"'"
            },
            "spec": {
                "replicas": 1,
                "selector": {
                    "matchLabels": {
                        "app": "nginx"
                    }
                },
                "template": {
                    "metadata": {
                        "labels": {
                            "app": "nginx"
                        }
                    },
                    "spec": {
                        "nodeName": "'"${ip}"'",
                        "containers": [
                            {
                                "name": "nginx",
                                "image": "hub.paas/base/nginx:1.21.0",
                                "ports": [
                                    {
                                        "containerPort": '"${CONTAINER_PORT}"'
                                    }
                                ]
                            }
                        ],
                        "nodeSelector": {
                            "kubernetes.io/hostname": "'"${ip}"'"
                        }
                    }
                }
            }
        }' >/dev/null 2>&1
}

# 创建Service
create_nginx_service() {
    curl -s -k -X POST \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer ${TOKEN}" \
        http://${APISERVER}/api/v1/namespaces/${NAMESPACE}/services \
        -d '{
            "apiVersion": "v1",
            "kind": "Service",
            "metadata": {
                "name": "'"${SERVICE_NAME}"'"
            },
            "spec": {
                "selector": {
                    "app": "nginx"
                },
                "ports": [
                    {
                        "protocol": "TCP",
                        "port": 80,
                        "targetPort": '"${CONTAINER_PORT}"'
                    }
                ],
                "type": "NodePort"
            }
        }' >/dev/null 2>&1 
}

# 检查Pod状态
check_pod_status() {
    kubectl get pods -l app=nginx --kubeconfig="${KUBECONFIG}" -n ${NAMESPACE} -o jsonpath='{.items[*].status.phase}' | grep -q "Running"
    return $?
}

# 执行7层健康检查
health_check() {
    NODE_PORT=$(kubectl get svc ${SERVICE_NAME} --kubeconfig="${KUBECONFIG}" -n ${NAMESPACE} -o jsonpath='{.spec.ports[0].nodePort}')
    curl -s -o /dev/null -w "%{http_code}" http://${ip}:${NODE_PORT} >/dev/null 2>&1 
    return $?
}

# 清理资源
cleanup() {
    kubectl delete deployment ${DEPLOYMENT_NAME} --kubeconfig="${KUBECONFIG}" -n ${NAMESPACE} >/dev/null 2>&1
    kubectl delete service ${SERVICE_NAME} --kubeconfig="${KUBECONFIG}" -n ${NAMESPACE} >/dev/null 2>&1
}


# 主流程
# 用户输入判断
check_user_input
#echo -e "${YELLOW}检查节点: ${ip} 是否存在与集群...${NC}"
if check_node_exists; then
    echo -e "${GREEN}节点存在,创建 deploy:${DEPLOYMENT_NAME} services:${SERVICE_NAME}...${NC}"
    create_nginx_deployment 
    create_nginx_service 
    echo -e "${GREEN}资源已创建,等待启动运行 10s...${NC}"
    sleep 10
    if check_pod_status; then
        #echo -e "${GREEN}应用启动成功,检查七层接口状态...${NC}"
        if health_check; then
            echo -e "${GREEN}应用启动成功,服务探测健康,状态码返回: 200${NC}"
            echo -e "${YELLOW}资源清理${NC}"
            cleanup
            exit 0
        else
            echo -e"${RED}服务探测健康失败,节点网络异常...${NC}"
            echo -e "${YELLOW}资源清理${NC}"
            cleanup
            exit 1
        fi
    else
        echo -e "${RED}应用启动失败,节点存在异常...${NC}"
        cleanup
        exit 1
    fi
else
    echo -e "${RED}节点 ${ip} 不属于集群...${NC}"
    exit 1
fi


